package com.juma.cartridge.retryque.aop;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.springframework.beans.factory.BeanFactory;

import com.juma.cartridge.common.HessianIOUtils;
import com.juma.cartridge.retryque.IntervalRetryHandler;
import com.juma.cartridge.retryque.RetryResult;
import com.juma.cartridge.retryque.RetryTask;

public class AspectRetryHandler extends IntervalRetryHandler {

	private BeanFactory beanFactory;
	private Method retryMethod;
	private int max;
	
	public AspectRetryHandler(BeanFactory beanFactory,Method method,int max) {
		this.retryMethod = method;
		this.beanFactory = beanFactory;
		this.max = max;
	}


	@Override
	protected RetryResult doRetry(RetryTask task) {
		if(task.getRetries()>max) {
			return RetryResult.BROKEN;
		}
		try {
			Object[] args = HessianIOUtils.deserialize(task.getBizBin());
			Class<?> beanClass = retryMethod.getDeclaringClass();
			Object bean = beanFactory.getBean(beanClass);
			if(bean==null) {
				task.setDetail("BeanFactory中未找到"+beanClass.getName()+"类型的bean");
				return RetryResult.BROKEN;
			}
			RetryTaskHolder.O.set(task);
			retryMethod.invoke(bean, args);
			return RetryResult.OVER;
		}catch(InvocationTargetException ite) {
			task.setDetail(ite.getTargetException().getMessage());
			return RetryResult.RETRY;
		}catch(Exception e) {
			task.setDetail(e.getMessage());
			return RetryResult.RETRY;
		}finally {
			RetryTaskHolder.O.remove();
		}
	}
}
